<template>
  <el-popover
    trigger="click"
    popper-class="picker-popover"
    :offset="offset"
  >
    <el-input 
      slot="reference"
      :value="months" 
      placeholder="请选择月份"
      @clear="handle_clear"
      @click.native="initPicker([])"
      clearable
    ></el-input>
    <div id="month-picker"></div>
  </el-popover>
</template>
<script>
import AirDatepicker from 'air-datepicker'
import 'air-datepicker/air-datepicker.css'
import zh from 'air-datepicker/locale/zh';
export default {
  name: 'MonthsPicker',
  props: {
    monthsValue: {
      type: String,
      default: ''
    },
    valueFormat: {
      type: String,
      default: 'yyyyMM'
    },
    offset: {
      type: Number,
      default: 0
    }
  },
  data(){
    return {
      months: '',
      monthsPicker: null,
    }
  },
  watch: {
    monthsValue: {
      // immediate: true,
      handler(val){
        let selectedDates = val === '' ? [] : val.split(",").map(it => {
          return this.moment(it).format("yyyy-MM");
        });
        this.initPicker(selectedDates);
        this.months = selectedDates.toString();
      }
    }
  },
  methods: {
    initPicker(selectedDates){
      if(this.monthsPicker !== null) return;
      let clearBtn = {
        content: '清空选择',
        onClick: this.handle_clear
      }
      this.monthsPicker = new AirDatepicker("#month-picker", {
        locale: zh,
        view:'months',
        minView: 'months',
        multipleDates: true,
        dateFormat: 'yyyy-MM',
        onSelect: this.handle_select,
        buttons: [clearBtn],
        selectedDates
      })
    },
    handle_select({formattedDate}){
      let months = formattedDate.map(it => {
        return this.moment(it).format(this.valueFormat);
      }).toString();

      this.$emit("update:monthsValue", months);
    },
    handle_clear(){
      const { monthsPicker } = this;
      if(monthsPicker === null) return;
      monthsPicker.setViewDate(null);
      this.$nextTick(() => {
        monthsPicker.setViewDate(new Date());
      })
      monthsPicker.selectedDates = [];
      this.$emit("update:monthsValue", '');
    }
  }
}
</script>
<style lang="scss">
.el-popover.picker-popover {
  padding: 0;
  .popper__arrow {
    left: 80px !important;
  }
}
</style>